# coding:utf-8
import os

from base import Base


class Admin(Base):
    def __init__(self, userName, user_json, gift_json):
        self.userName = userName
        super().__init__(user_json, gift_json)
        self.get_user()

    def get_user(self):
        # 调用base的查询方法
        users = self._Base__read_users()
        current_user = users.get(self.userName)
        if current_user == None:
            raise ValueError('该用户 %s 不存在' % self.userName)

        if current_user.get('status') == False:
            raise ValueError('该用户 %s 已被封禁' % self.userName)

        if current_user.get('roles') != 'admin':
            raise ValueError('不是管理员')

        self.user = current_user
        self.role = current_user.get('roles')
        self.name = current_user.get('userName')
        self.status = current_user.get('status')

    def add_user(self, userName, userPassword, roles):
        if self.role != 'admin':
            raise Exception('不是管理员')

        self._Base__write_user(userName=userName, userPassword=userPassword, roles=roles)

    def update_user(self, userName, roles, status=True):
        self.__check('不是管理员')
        self._Base__update_user(userName=userName, role=roles, status=status)

    def delte_user(self, userName):
        self.__check('不是管理员')
        self._Base__delete_user(userName=userName)

    def add_gift(self, first_level, sencond_level, gift_name, gift_count):
        self.__check("不是管理员")
        self._Base__write_gift(first_level=first_level, sencond_level=sencond_level,
                               gift_name=gift_name, gift_count=gift_count)

    def read_gift(self):
        self.__check("不是管理员")
        gift = self._Base__read_gifts()
        return gift

    def delete_gift(self, first_level, sencond_level, gift_name, ):
        self.__check("不是管理员")
        self._Base__delete_gift(first_level, sencond_level, gift_name)

    def update_gift(self, first_level, sencond_level,
                    gift_name, gift_count=1):
        self.__check("不是管理员")
        self._Base__gift_update(userName=self.userName, first_level=first_level, second_level=sencond_level,
                                gift_name=gift_name, gift_count=gift_count)

    def __check(self, message):
        self.get_user()
        if self.role != 'admin':
            raise Exception(message)


if __name__ == '__main__':
    user_path = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'storage', 'user.json')
    gift_path = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'storage', 'gift.json')
    admin = Admin('jie', user_path, gift_path)
    print(admin.userName, admin.role, admin.status)
    admin.add_gift(first_level='level1', sencond_level='level1',
                      gift_name='iPhone14 Pro Max',gift_count=66)
